import 'package:flutter/material.dart';

import 'package:flutter_fronter_service/model/cart_entity.dart';
import 'package:flutter_fronter_service/model/sku_entity.dart';
import 'package:flutter_fronter_service/tools/commons.dart';
import 'package:get/get.dart';

import '../controller/userController.dart';
import '../model/properties_entity.dart';
import '../api/cartApi.dart';
class CartPage extends StatefulWidget {
  const CartPage({super.key});

  @override
  State<CartPage> createState() => _CartPageState();
}

class _CartPageState extends State<CartPage> {

  final RxList<Map<String, dynamic>> selectedProducts = RxList<Map<String, dynamic>>();
  bool isLogin =  false;
  bool isLoading = true;
  UserController userController = Get.find<UserController>();
  final RxList<bool> selected = RxList<bool>();

  //初始化购物车列表
  late List<CartEntity> cartList = [];
  Future<void> _initCart() async {

    if(userController.user.value.id>0){
      //判断是否登录
      isLogin = true;
      //请求
      var res = await getAllCartApi();

      for(int i = 0,l = res["data"].length; i < l; i++){
        late Rx<String> goodsSpec = "".obs;
        late RxList<PropertiesEntity> itemSpecList = <PropertiesEntity>[].obs;
        //获取sku信息
        SkuEntity sku = SkuEntity.fromJson(res["data"][i]["skuItemVo"]);
        (res["data"][i].remove("skuItemVo"))["itemSpec"].forEach((item)=>itemSpecList.add(PropertiesEntity.fromJson(item)));
        sku.itemSpec = itemSpecList;
        //初始购物车
        CartEntity cart = CartEntity.fromJson(res["data"][i]);

        itemSpecList.forEach((element) {
          goodsSpec.value = goodsSpec.value +' '+ element.value;
        });

        cart.spec = goodsSpec.value;
        cart.skuEntity = sku;
        cartList.add(cart);
      }

      selected.value = List<bool>.filled(cartList.length, false);
    }

    isLoading = false;
    setState(() {
    });
  }

  @override
  void initState() {
    super.initState();
    _initCart();
  }

  double get totalPrice {
    double total = 0;
    for (int i = 0; i < cartList.length; i++) {
      if (selected[i]) {
        total += cartList[i].skuEntity.goodsPrice * cartList[i].quantity;
      }
    }
    return total;
  }

  void selectAll(bool value) {
    selected.value = List<bool>.filled(cartList.length, value);
    updateSelectedProducts();
  }


  void updateSelectedProducts() {
    selectedProducts.clear();
    for (int i = 0; i < cartList.length; i++) {
      if (selected[i]) {
        selectedProducts.add({'id': cartList[i].skuEntity.id, 'count': cartList[i].quantity,'cartId':cartList[i].id});
      }
    }
    print('Selected products: $selectedProducts');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('购物车'),
        centerTitle: true,
      ),
      body: isLogin?(isLoading ? const Center(child: CircularProgressIndicator()) :ListView.builder(
        itemCount: cartList.length,
        itemBuilder: (context, index) {
          return Obx(() {
            return Card(
              margin: EdgeInsets.all(8),
              child: ListTile(
                leading: Checkbox(
                  value: selected[index],
                  onChanged: (bool? value) {
                    selected[index] = value!;
                    updateSelectedProducts();
                  },
                ),
                title: Row(
                  children: [
                    Image.network(
                      cartList[index].skuEntity.itemImg,
                      width: 50,
                      height: 50,
                      fit: BoxFit.cover,
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(cartList[index].skuEntity.goodsName,
                              style: TextStyle(
                                  fontSize: 16, fontWeight: FontWeight.bold)),
                          Text(cartList[index].spec),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('¥${cartList[index].skuEntity.goodsPrice}',
                                  style: TextStyle(color: Colors.red)),
                              Text('x  ${cartList[index].quantity}'),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          });
        },
      )):Center(
        child: Text("未登录"),
      ),
      bottomNavigationBar: Obx(() {
        return Container(
          padding: EdgeInsets.all(16),
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Checkbox(
                    value: selected.every((element) => element),
                    onChanged: (bool? value) {
                      selectAll(value!);
                    },
                  ),
                  Text('全选'),
                ],
              ),
              Text('总价：¥${totalPrice.toStringAsFixed(2)}',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
              ElevatedButton(
                onPressed: () {
                  // 结算时，购物车不能为空
                  if(selectedProducts.isNotEmpty){
                    Get.toNamed("/confirmOrder",arguments: {"sku":selectedProducts});
                  }else{
                    CommonUtils.showToast("购物车不能为空");
                  }

                },
                child: Text('结算'),
              ),
            ],
          ),
        );
      }),
    );
  }
}

